package com.sxj.corejava.code12_jdbc;

import com.sxj.corejava.util.DataAccessException;
import com.sxj.corejava.util.JDBCUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 石小俊
 * @date 2024年07月03日 11:00
 */
public class Test12_元数据 {

    public static void main(String[] args) throws DataAccessException {
//        selectAll();
        User user = new User("lucy", "666666", "13912345677", "江苏-无锡");
        insertReturnPrimaryKey(user);
    }

    public static void test01() {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            conn = JDBCUtil.getConnection();

            // 获取数据库元数据
            DatabaseMetaData dbmd = conn.getMetaData();
            System.out.println("数据库产品名:" + dbmd.getDatabaseProductName());
            System.out.println("数据库版本号:" + dbmd.getDatabaseProductVersion());
            System.out.println("数据库驱动:" + dbmd.getDriverName());
            System.out.println("数据库驱动版本:" + dbmd.getDriverVersion());
            System.out.println("数据库url:" + dbmd.getURL());
            System.out.println("数据库用户名:" + dbmd.getUserName());
            System.out.println("数据库的默认事务隔离级别:" + dbmd.getDefaultTransactionIsolation());
            System.out.println("获取可用于转义通配符的字符串:" + dbmd.getSearchStringEscape());

            String sql = new StringBuffer()
                    .append(" select id,username,password,phone,address ")
                    .append(" from t_user ")
                    .toString();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            int count = rsmd.getColumnCount();
            System.out.println("结果集总列数:" + count);
            for (int i = 1; i <= count; i++) {
                System.out.println("第" + i + "列的列名:" + rsmd.getColumnName(i));
                System.out.println("第" + i + "列的列类型:" + rsmd.getColumnTypeName(i));
                System.out.println("第" + i + "列的列所在的表:" + rsmd.getTableName(i));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static List<Emp> selectAll() throws DataAccessException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Emp> emps = new ArrayList<>();

        try {
            conn = JDBCUtil.getConnection();
            String sql = new StringBuffer()
                    .append(" select e.id,e.name,e.salary,d.id 'd.id',d.name 'd.name',d.remark ")
                    .append(" from t_emp e ")
                    .append(" left join t_dept d ")
                    .append("  on e.dept_id = d.id")
                    .toString();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            int count = rsmd.getColumnCount();
            System.out.println("结果集总列数:" + count);
            for (int i = 1; i <= count; i++) {
                System.out.println("第" + i + "列的列名:" + rsmd.getColumnName(i));
                System.out.println("第" + i + "列的列类型:" + rsmd.getColumnTypeName(i));
                System.out.println("第" + i + "列的列所在的表:" + rsmd.getTableName(i));
            }
        } catch (DataAccessException e) {
            e.printStackTrace();
            throw e;
        } catch (SQLException e) {
            e.printStackTrace();
            throw new DataAccessException("数据访问异常");
        } finally {
            JDBCUtil.close(conn, ps, rs);
        }

        return emps;
    }

    public static Integer insertReturnPrimaryKey(User user) throws DataAccessException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Integer id = null;

        try {
            conn = JDBCUtil.getConnection();
            String sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_user ")
                    .append("   (username,password,phone,address)")
                    .append(" values ")
                    .append("   (?,?,?,?)")
                    .toString();
            // 在获取状态集时,可以通过参数二表示是否返回自动生成的键
            // 其值有两种:
            // 1.Statement.RETURN_GENERATED_KEYS:返回
            // 2.Statement.NO_GENERATED_KEYS:不返回
            // PreparedStatement是Statement的子类,可以调用父类常量
            ps = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getPhone());
            ps.setString(4, user.getAddress());
            ps.executeUpdate();
            rs = ps.getGeneratedKeys();
            ResultSetMetaData rsmd = rs.getMetaData();
            int count = rsmd.getColumnCount();
            System.out.println("结果集总列数:" + count);
            for (int i = 1; i <= count; i++) {
                System.out.println("第" + i + "列的列名:" + rsmd.getColumnName(i));
                System.out.println("第" + i + "列的列类型:" + rsmd.getColumnTypeName(i));
                System.out.println("第" + i + "列的列所在的表:" + rsmd.getTableName(i));
            }
        } catch (DataAccessException e) {
            e.printStackTrace();
            throw e;
        } catch (SQLException e) {
            e.printStackTrace();
            throw new DataAccessException("数据访问异常");
        } finally {
            JDBCUtil.close(conn, ps, rs);
        }

        return id;
    }
}
